package com.songshuang.myutilsboot.stlf.util;


import com.songshuang.myutilsboot.stlf.io.Constants;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class LogWriter {
    private LogWriter() {}

    public static void ensureDirs() {
        mkdir(Constants.FORCAST_RES_PATH);
        mkdir(Constants.ANN_MODEL_PATH);
        mkdir(Constants.LOG_PATH);
    }

    public static void mkdir(String dir) {
        try {
            Files.createDirectories(Paths.get(dir));
        } catch (IOException ignored) {}
    }

    public static int write(String title, String msg) {
        ensureDirs();
        String file = Constants.LOG_PATH + "op_log_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".log";
        File f = new File(file);
        try (FileWriter fw = new FileWriter(f, true)) {
            fw.write("======开始=========================================================================\n");
            fw.write("time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\ttitle:" + title + "\n");
            fw.write("message:" + (msg == null ? "" : msg) + "\n");
            fw.write("======结束=========================================================================\n");
            fw.flush();
            rotateIfTooLarge(f);
            return 0;
        } catch (IOException e) {
            return -1;
        }
    }

    private static void rotateIfTooLarge(File f) throws IOException {
        long max = 50L * 1024 * 1024;
        if (f.length() <= max) return;
        String name = f.getName();
        String base = name.substring(0, name.lastIndexOf('.'));
        String ext = name.substring(name.lastIndexOf('.'));
        int idx = 1;
        while (true) {
            Path newPath = Paths.get(f.getParent(), base + "_" + idx + ext);
            if (!Files.exists(newPath)) {
                Files.move(f.toPath(), newPath);
                Files.createFile(f.toPath());
                break;
            }
            idx++;
        }
    }
}


